using System.IO;
using System.Reflection;
using Drill.Core.Utilities;

namespace Drill.TestSupport
{
    public class TestDataDirectoryLocator
    {
        private const string TestDataDirectoryName = "TestData";
	    private const int MaxParentDirectoryTraversals = 6;

        public static string FindTestDataDirectory()
        {
            // Check to see if the test data directory exists:
            // 1. Start checking to see if it is a subdirectory 
			//    of the same directory in which the assembly resides.
            // 2. Traverse up one directory level and re-check iteratively 
			//    until the test data directory is found, until the 
			//    maximum number of directory traversals is reached or 
			//    until the current directory doe not exist.

			int attempt = 0;
            Assembly assembly = Assembly.GetExecutingAssembly();
			string currentDirectory = Path.GetDirectoryName(assembly.Location);

			while (attempt <= MaxParentDirectoryTraversals)
			{
				if (string.IsNullOrWhiteSpace(currentDirectory) || false == Directory.Exists(currentDirectory))
				{
					break;
				}

				string testDataDirectory = Path.Combine(currentDirectory, TestDataDirectoryName);
				if (Directory.Exists(testDataDirectory))
				{
					return testDataDirectory;
				}
				
				currentDirectory = PathUtility.GetParentPath(currentDirectory);
				
				attempt++;
			}

            return null;
        }
    }
}
